(function(angular) {
	'use strict';
	angular.module('fs.waf').factory('companyService', companyService);
	companyService.$inject = [ '$q', 'Constants', 'loggerFactory', 'commonService', 'ajaxServiceFactory', 'modalService', 'gridService', 'arithService','$filter', 'storageService' ];
	function companyService($q, Constants, loggerFactory, commonService, ajaxServiceFactory, modalService, gridService, arithService, $filter, storageService) {
		var log = loggerFactory.getLogger("companyService"), ajaxService = ajaxServiceFactory.buildAjaxService({
			getCompanyOptions : {
				url : 'do/cda/dataList/companyOptions',
				method : 'get'
			}
		});
		
		function dateDisabled(dateModel) {
			var date = dateModel.date, mode = dateModel.mode;
			return mode === 'day' && commonService.isHoliday(date);
		}
		
		function getCompanyOptions() {
			var defer = $q.defer();
			ajaxService.getCompanyOptions().then(function(response) {
				var companyOptions = {};
				if (response.data) {
					angular.forEach(response.data, function(value, key) {
						var tempValue = {};
						tempValue.data = value;
						companyOptions[key] = tempValue;
					});
				}
				defer.resolve(companyOptions);
			});
			return defer.promise;
		}
		
		
		function initGeneral($scope, ctrl, obj, updateProcessFlag) {
			var defer = $q.defer();
			ctrl.moreAddress ={};
			ctrl.removeAllCallback = function (resultData) {
				var defer = $q.defer();
				modalService.openConfirmDialogs({
					'messages' : [ 'title.dialog.confirm.deletedata' ],
					'btnCallback' : {
						'ok' : function() {
							if(ctrl.company.companyProps){
								ctrl.company.companyProps = [];
							}
							var compangTypes = ctrl.company.companyTypes;
							for (var i = compangTypes.length - 1; i >= 0 ; i--) {
								var companyType = compangTypes[i];
								for (var j = resultData.length - 1; j >= 0 ; j--) {
									if(companyType == resultData[j]){
										compangTypes.splice(i, 1);
									}
								}
							}
							ctrl.changeCompanyType(compangTypes);
							defer.resolve();
						},
						'close' : function() {
							return;
						}
					}
				});
				return defer.promise;
			}
			ctrl.removeCallback = function (resultData) {
				var defer = $q.defer();
				modalService.openConfirmDialogs({
					'messages' : [ 'title.dialog.confirm.deletedata' ],
					'btnCallback' : {
						'ok' : function() {
							if(ctrl.company.companyProps){
								ctrl.company.companyProps = [];
							}
							var compangTypes = ctrl.company.companyTypes;
							for (var i = compangTypes.length - 1; i >= 0 ; i--) {
								var companyType = compangTypes[i];
								for (var j = resultData.length - 1; j >= 0 ; j--) {
									if(companyType == resultData[j]){
										compangTypes.splice(i, 1);
									}
								}
							}
							ctrl.changeCompanyType(compangTypes);
							defer.resolve();
						},
						'close' : function() {
							return;
						}
					}
				});
				return defer.promise;
			}
			
			ctrl.moreAddress.activeIndex = 0;
			ctrl.redirrctToAddress = function(){
				ctrl.moreAddress.activeIndex = 8;
			}
			
			ctrl.changeCompanyType = function(value){
				var formConfigs = ctrl.layoutConfig.formConfigs;
				var companyTypes = ctrl.company.companyTypes ? ctrl.company.companyTypes : [];
				if (formConfigs) {
					var custProfAvaiProps = [];
					ctrl.company.companyProps;
					angular.forEach(formConfigs.general.gridConfigs, function(gridConfig, key) {
						//filter dynaparms by companyTypes
						if (gridConfig.dynamicParameter && gridConfig.dynamicParameter.companyTypes != null) {
							var flag = true;
							for(var i = 0; i < companyTypes.length; i++){
								if(gridConfig.dynamicParameter.companyTypes.indexOf(companyTypes[i]) != -1){
									flag = false;
									break;
								}
							}
							if(flag){
								formConfigs.general.gridConfigs[key].active = false;
							}else{
								formConfigs.general.gridConfigs[key].active = true;
							}
						}
						
					});
					angular.forEach(formConfigs.custProfile.gridConfigs, function(gridConfig, key) {
						//filter dynaparms by companyTypes
						if (gridConfig.dynamicParameter && gridConfig.dynamicParameter.companyTypes != null) {
							var flag = true;
							var dynaParm = angular.copy(gridConfig);
							if(companyTypes.length == 0){
								flag = false;
							}
							for(var i = 0; i < companyTypes.length; i++){
								if(gridConfig.dynamicParameter.companyTypes.indexOf(companyTypes[i]) != -1){
									flag = false;
									break;
								}
							}
							if(!flag){
								custProfAvaiProps.push(dynaParm);
							}
						}
					});
					ctrl.availableProperties = custProfAvaiProps;
				}
			};
		
			ctrl.companyNoChanged = function() {
				if (ctrl.company.companyNo) {
					if (!ctrl.company.companyCode || ctrl.company.companyCode.indexOf(Constants.ENCODE_SEPARATOR) == -1) {
						ctrl.company.companyCode = ctrl.company.siteCode + ctrl.company.companyNo;
					}
				} else {
					ctrl.company.companyCode = "";
				}
				resetThemeNameOption();
			};
			function resetThemeNameOption() {
				if (ctrl.themeNameOptions && ctrl.themeNameOptions.data) {
					for (var i = 0; i < ctrl.themeNameOptions.data.length; i++) {
						if (ctrl.themeNameOptions.data[i].label == 'Customized') {
							ctrl.themeNameOptions.data[i].value = $filter('encode')(ctrl.company.companyCode);
						}
					}
				}
			}
			ctrl.dateDisabled = companyService.dateDisabled;
			
			ctrl.classificationCodeChanged = function(company, form, isInit){
				if(isInit){
					return;
				}
				var classificationCode = getClassificationStage(ctrl.classifiOptions, company.classificationCode);
				if("NPL" == classificationCode){
					company.dateNpl = storageService.getSiteInfo().eodDate;
				}else{
					company.dateNpl = undefined;
				}
			};
		
			getCompanyOptions().then(function(response) {
				ctrl.companyStatusOptions = response.companyStatusOptions;
				ctrl.timezoneOptions = response.timezoneOptions;
				ctrl.companyCountryOptions = response.companyCountryOptions;
				ctrl.companyClassOptions = response.companyClassOptions;
				ctrl.industryCodeOptions = response.industryCodeOptions;
				ctrl.localeCodeOptions = response.localeCodeOptions;
				ctrl.backendOnlyOptions = response.backendOnlyOptions;
				ctrl.themeNameOptions = response.themeNameOptions;
				ctrl.boCodeOptions = response.boCodeOptions;
				ctrl.uccFileFlagOptions = response.uccFileFlagOptions;
				ctrl.complianceStatusOptions = response.complianceStatusOptions;
				ctrl.ewsPartyFlagOptions = response.ewsPartyFlagOptions;
				ctrl.custTypeOptions = response.custTypeOptions;
				ctrl.segmentCodeOptions = response.segmentCodeOptions;
				ctrl.localFlagOptions = response.localFlagOptions;
				ctrl.fiFlagOptions = response.fiFlagOptions;
				//for companyEdiFileType
				ctrl.companyEdiFileTypeOptions = response.companyEdiFileTypeOptions;
				ctrl.yesOrNoOptions = response.yesOrNoOptions;
				ctrl.ediFileDeliYesOrNoOptions = response.yesOrNoOptions;
				ctrl.overrideSiteIdOptions = response.yesOrNoOptions;
				ctrl.classifiOptions = response.classifiOptions.data;
				ctrl.ediProfileTypeOptions = response.ediProfileTypeOptions;
				
				if (ctrl.themeNameOptions && ctrl.themeNameOptions.data) {
					for (var i = 0; i < ctrl.themeNameOptions.data.length; i++) {
						if (ctrl.themeNameOptions.data[i].label == 'Customized') {
							ctrl.themeNameOptions.data[i].value = $filter('encode')(obj.companyCode);
						}
					}
				}
				
				defer.resolve();
			}, angular.noop);
			// for attachment
			ctrl.getAttachmentList = function() {
				ctrl.company = ctrl.company || {};
				var dataStatus = ctrl.company.dataStatus || '';
				var params = {
					'srcTxnType' : ctrl.company.currentDataType,
					'srcTxnRef' : $filter('encode')(ctrl.company.companyCode),
					'isViewPage': !updateProcessFlag,
					'storeTempTableFlag' : ctrl.company.dataActive != 'Y',
					'entity' :  ctrl.company, //when store to temp Table the entity property is required.
					'relatedDocIdsProp': 'tempDocIds'//the default relatedDocIdsProp is tempDocIds, it is the property in the voCompany. 
				};
				commonService.getAttachmentList(params);
			};
			return defer.promise;
		}
		
		function getClassificationStage(classifiOptions, classificationCode){
			if(classifiOptions && classifiOptions.length > 0){
				for (var i = 0; i < classifiOptions.length; i++) {
					if(classifiOptions[i].value == classificationCode){
						return classifiOptions[i].extProperty;
					}
				}
			}
		}
		
		function initContact($scope, ctrl, updateProcessFlag) {
			// init serviceCode select
			ctrl.companyContact = {};
			//init companyContacts
			ctrl.contactInnerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.contact.tableConfigs.table, contactRowSelectionChanged);
			ctrl.contactInnerGridOptions.data = 'vm.company.companyContacts';
			ctrl.contactInnerGridOptions.verifyData = 'vm.companyOld.companyContacts';
			function contactRowSelectionChanged(eventRow, selectedRows) {
				ctrl.selectedContacts = selectedRows;
			}
			
			ctrl.addContact = function(row) {
				return $q(function(resolved, rejected){
					if (!ctrl.company.companyContacts) {
						ctrl.company.companyContacts = [];
					}
					var item = {
					};
					item.companyCode = $filter('encode')(ctrl.company.companyCode);
					item.companyTypes = ctrl.company.companyTypes;
					modalService.openCustomDialogs({
						'dialogsModule' : 'cda.company.contactEdit',
						'params' : item,
						'btnCallback' : {
							'ok' : function(contactCtrl) {
								contactCtrl.companyContact.dataStatus = 'C';
								angular.extend(row, contactCtrl.companyContact);
								row.companyCode = $filter('encode')(ctrl.company.companyCode);
								resolved();
							},
							'close' : function(){
								rejected();
							}
						}
					});
				});
				
			};

			ctrl.editContact = function(row) {
				modalService.openCustomDialogs({
					'dialogsModule' : 'cda.company.contactEdit',
					'params' : row.entity,
					'btnCallback' : {
						'ok' : function(contactCtrl) {
							if (!(contactCtrl.companyContact.dataStatus == 'C' || contactCtrl.companyContact.dataStatus == 'U')) {
								if (updateProcessFlag) {
									contactCtrl.companyContact.dataStatus = 'U';
								} else {
									contactCtrl.companyContact.dataStatus = 'C';
								}
							}
							angular.extend(row, contactCtrl.companyContact);
						}
					}
				});
			};
			
			
			ctrl.viewContact = function(row) {
				row.entity.readOnly = true;
				modalService.openCustomDialogs({
					'dialogsModule' : 'cda.company.contactEdit',
					'params' : row.entity 
				});
			};
		}
		function initService($scope, ctrl, updateProcessFlag) {
			//init services
			ctrl.serviceInnerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.service.tableConfigs.table, serviceRowSelectionChanged);
			ctrl.serviceInnerGridOptions.data = 'vm.company.services';
			ctrl.serviceInnerGridOptions.verifyData  = 'vm.companyOld.services';
			function serviceRowSelectionChanged(eventRow, selectedRows) {
				ctrl.selectedServices = selectedRows;
			}
			
			ctrl.addService = function(row) {
				return $q(function(resolved, rejected){
					var existServices = ctrl.company.services;
					modalService.openCustomDialogs({
						   'title': 'title.company.service.lookup',
						   'dialogsModule' : 'cda.component',
						   'params':{multiSelect : true, services: existServices, isCompany : 'Y'},
						   'btnCallback' : {
								'ok' : function(service) {			
									if (!ctrl.company.services) {								
										ctrl.company.services = [];
									}
									var exist = false;
									for (var i = 0; i < ctrl.company.services.length; i++) {
										var item = ctrl.company.services[i];
										if (item.serviceCode == service.serviceCode) {									
											exist = true;
											break;
										}
									}
									if (!exist) {	
										service.dataStatus = 'C';
										angular.extend(row, service);
										resolved();
									}	
								},
								'close' : function(){
									rejected();
								}
							}				   
						});	
				});
						
			}
			
			ctrl.editService = function(row) {
				modalService.openCustomDialogs({
				   'title': 'title.company.service.lookup',
				   'dialogsModule' : 'cda.component',
				   'params':{multiSelect : true, service: angular.copy(row.entity), isCompany : 'Y'},
				   'btnCallback' : {
						'ok' : function(service) {			
							if (!ctrl.company.services) {								
								ctrl.company.services = [];
							}
							var exist = false;
							for (var i = 0; i < ctrl.company.services.length; i++) {
								var item = ctrl.company.services[i];
								if ( item.dataStatus == 'C') {			//createContinue
									if (item.serviceCode == service.serviceCode) {	
										if ( item.companyServCmpts != service.companyServCmpts) {
//											row.entity = ctrl.company.services[i] = service;
											angular.extend(row.entity, service);
											row.entity.dataStatus = 'C';
											exist = true;
											break;
										}
									}
								} else {								//update
									if (item.serviceCode == service.serviceCode) {	
										if ( item.companyServCmpts != service.companyServCmpts) {
											angular.extend(row.entity, service);
											row.entity.dataStatus = 'U';
											exist = true;
											break;
										}
									}
								}
							}	
							if (!exist) {									
								throw "unexpected error";
							}	
						}
					}				   
				});	
			}
			
			
			ctrl.viewService = function(row) {
				if (row.entity) {
					var service = row.entity;
					if (service.companyServCmpts && service.companyServCmpts.length) {
						modalService.openCustomDialogs({
							   'title': 'title.company.service.lookup',
							   'dialogsModule' : 'cda.componentView',
							   'params':{service: service}			   
							});						
					} else {
						authService.getCompanyService(service).then(function(response) {
							service = response.data;
							modalService.openCustomDialogs({
								   'title': 'title.company.service.lookup',
								   'dialogsModule' : 'cda.componentView',
								   'params':{service: service}			   
								});							
						});
					}
				}
			}	
		}
		
		function initSubCompany($scope, ctrl) {
			//init subcompany grid
			ctrl.subCompanyInnerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.subCompany.tableConfigs.table, subCompanyRowSelectionChanged);
			ctrl.subCompanyInnerGridOptions.data = 'vm.company.subCompanies';
			ctrl.subCompanyInnerGridOptions.verifyData = 'vm.companyOld.subCompanies';
			function subCompanyRowSelectionChanged(eventRow, selectedRows) {
				ctrl.selectedSubCompanies = selectedRows;
			}
			
			ctrl.addSubCompany = function(row) {
				return $q(function(resolved, rejected){
					// params
					var params = {};
					params.subCompanies = row.entity;
					params.filterCompanyCodes = [];
					angular.forEach(ctrl.company.subCompanies, function(subCompany, index) {
						params.filterCompanyCodes.push($filter('encode')(subCompany.childCompanyCode));
					});
					if(ctrl.company.companyCode){
						params.workingCompanyCode = $filter('encode')(ctrl.company.companyCode);
					}
					params.multiSelect = true;
					params.isSite ='false';
					modalService.openCustomDialogs({
					   'title': 'title.company.lookup',
					   'dialogsModule' : 'cda.company',
					   'params':  params,
					   'btnCallback' : {
							'ok' : function(selectedRows) {			
								if (!selectedRows || selectedRows.length == 0) {
									modalService.openErrorDialogs({
										messages : [ 'js.info.common.item-need-first-select' ]
									});
									return false;
								}							
								if (!ctrl.company.subCompanies) {								
									ctrl.company.subCompanies = [];
								}
								angular.forEach(selectedRows, function(selectedRow, index) {
									selectedRow.dataStatus = 'C';
									selectedRow.childCompanyCode = selectedRow.companyCode;
									selectedRow.companyCode = ctrl.company.companyCode;
									ctrl.company.subCompanies.push(selectedRow);
								});
								
							},
							'close' : function(){
								rejected();
							}
							
						}		
					});	
				});
						
			};
			
		}
		
		function initNotify($scope, ctrl, updateProcessFlag) {
			//init notify grid 
			ctrl.notifyInnerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.notify.tableConfigs.table, notifyRowSelectionChanged);
			ctrl.notifyInnerGridOptions.data = 'vm.company.notifies';
			ctrl.notifyInnerGridOptions.verifyData = 'vm.companyOld.notifies';
			function notifyRowSelectionChanged(eventRow, selectedRows) {
				ctrl.selectedNotifies = selectedRows;
			}
			
			ctrl.addNotify = function(row) {
				return $q(function(resolved, rejected){
					var params = {};
					params.services = [];
					for (var i = 0; i < ctrl.company.services.length; i++) {
						var service = ctrl.company.services[i];
						if (service.dataStatus == 'D') continue;
						params.services.push(service);
					}
					modalService.openCustomDialogs({
					   'title': 'title.company.notify',
					   'dialogsModule' : 'cda.companynotify.popupedit',
					   'params': params,
					   'btnCallback' : {
							'ok' : function(companyNotify) {							
								if (!ctrl.company.notifies) {
									ctrl.company.notifies = [];
								}
								companyNotify.dataStatus = 'C';
								angular.extend(row, companyNotify);
								resolved();
							},
							'close' : function(){
								rejected();
							}
						}		
					   
					});	
				});
						
			}
			
			ctrl.editNotify = function(row) {
				var params = {};
				params.notify = row.entity;
				params.services = [];
				for (var i = 0; i < ctrl.company.services.length; i++) {
					var service = ctrl.company.services[i];
					if (service.dataStatus == 'D') continue;
					params.services.push(service);
				}
				modalService.openCustomDialogs({
					   'title': 'title.company.notify',
					   'dialogsModule' : 'cda.companynotify.popupedit',
					   'params':  params,
					   'btnCallback' : {
							'ok' : function(companyNotify) {							
								if (!ctrl.company.notifies) {								
									ctrl.company.notifies = [];
								}
								if (!(companyNotify.dataStatus == 'C' || companyNotify.dataStatus == 'U')) {
									if (updateProcessFlag) {
										companyNotify.dataStatus = 'U';
									} else {
										companyNotify.dataStatus = 'C';
									}
								}
								angular.extend(row, companyNotify);
							}
						}		
					   
				});			
			}
			
			ctrl.viewNotify = function(row) {	
				var params = {};
				params.notify = row.entity;
				params.services = [];
				for (var i = 0; i < ctrl.company.services.length; i++) {
					var service = ctrl.company.services[i];
					if (service.dataStatus == 'D') continue;
					params.services.push(service);
				}
				if (ctrl.companyOld && ctrl.companyOld.notifies) {
					var oldModel4SelectedRow;
					angular.forEach(ctrl.companyOld.notifies, function(notify, index) {
						if (notify.companyNotifyId == params.notify.companyNotifyId) {
							oldModel4SelectedRow = notify;
						}
					});
					params.notifyOld = oldModel4SelectedRow;
				}
				modalService.openCustomDialogs({
				   'title': 'title.company.notify',
				   'dialogsModule' : 'cda.companynotify.popupview',
				   'params':params
				});
			}			
			
			
		}
		
		function initReport($scope, ctrl, updateProcessFlag) {
			// init serviceCode select
			ctrl.companyRpt = {};
			ctrl.serviceCodeOptions = {data:[]};
			$scope.$watch('vm.company.services', function(services) {
				if (services) {
					ctrl.serviceCodeOptions.data = [];
					for (var i = 0; i < services.length; i++) {
						var service = services[i];
						if (service.dataStatus == 'D') continue;
						var option = {
								label: $filter('encode')(service.serviceCode) + " - " + service.serviceName,
								value: $filter('encode')(service.serviceCode)
						};
						ctrl.serviceCodeOptions.data.push(option);
					}
				}
			}, true);
			$scope.$watch('vm.companyRpt.serviceCode', function(serviceCode) {
				if (serviceCode) {
					ctrl.company.companyRptsTmp = ctrl.company['companyRpts' + $filter('encode')(serviceCode)] || [];
					if(ctrl.companyOld) ctrl.companyOld.companyRptsTmp = ctrl.companyOld['companyRpts' + $filter('encode')(serviceCode)] || [];
				}
			});
			
			//init companyRpts
			ctrl.reportInnerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.report.tableConfigs.table, reportRowSelectionChanged);
			ctrl.reportInnerGridOptions.data = 'vm.company.companyRptsTmp';
			ctrl.reportInnerGridOptions.verifyData = 'vm.companyOld.companyRptsTmp';
			function reportRowSelectionChanged(eventRow, selectedRows) {
				ctrl.selectedCompanyRpts = selectedRows;
			}
			
			ctrl.addReport = function(row) {
				return $q(function(resolved, rejected){
					if (!ctrl.companyRpt.serviceCode) {
						modalService.openErrorDialogs({
							messages : [ 'js.info.company.servicecode-need-first-select' ]
						});
						return;
					}
					if (!ctrl.company.companyTypes ||ctrl.company.companyTypes.length == 0) {
						modalService.openErrorDialogs({
							messages : [ 'js.info.company.companytype-need-first-select' ]
						});
						return;
					}
					if (!ctrl.company.companyNo ) {
						modalService.openErrorDialogs({
							messages : [ 'js.info.company.companyno-need-first-select' ]
						});
						return;
					}
					var params = {};
					params.companyRpt = {report : {}};
					params.companyRpt.companyCode = $filter('encode')(ctrl.company.companyCode);
					params.companyRpt.report.serviceCode = ctrl.companyRpt.serviceCode;
					params.companyRpt.report.companyTypeList= ctrl.company.companyTypes;
					params.filterReportCodes = [];
					angular.forEach(ctrl.company.companyRpts, function(companyRpt, index) {
						params.filterReportCodes.push($filter('encode')(companyRpt.reportCode));
					});
					params.multiSelect = true;
					modalService.openCustomDialogs({
						   'title': 'title.company.report',
						   'dialogsModule' : 'cda.report',
						   'params': params,
						   'btnCallback' : {
								'ok' : function(selectedRows) {
									if (!selectedRows || selectedRows.length == 0) {
										modalService.openErrorDialogs({
											messages : [ 'js.info.common.item-need-first-select' ]
										});
										return false;
									}
									if (!ctrl.company.companyRpts) {								
										ctrl.company.companyRpts = [];
									}
									if (!ctrl.company['companyRpts' + $filter('encode')(ctrl.companyRpt.serviceCode)]) {
										ctrl.company['companyRpts' + $filter('encode')(ctrl.companyRpt.serviceCode)] = [];
									}
									angular.forEach(selectedRows, function(selectedRow, index) {
										selectedRow.report = selectedRow.report ||{};
										selectedRow.report.reportName = selectedRow.reportName;
										selectedRow.report.reportTitle = selectedRow.reportTitle;
										selectedRow.report.reportSubtitle = selectedRow.reportSubtitle;
										selectedRow.report.serviceCode = selectedRow.serviceCode;
										selectedRow.report.reportMode = selectedRow.reportMode;
										if(selectedRow.reportFormats){
											selectedRow.reportFormatsList = [];
											var fieldArr = selectedRow.reportFormats.split(",");
											for(var i = 0; i < fieldArr.length; i++){
												if(fieldArr[i] != ""){
													selectedRow.reportFormatsList.push(fieldArr[i]);
												}
											}
										}
										selectedRow.localeCode = selectedRow.localeCode || "en_US";
										selectedRow.dataStatus = 'C';
										selectedRow.companyCode = ctrl.company.companyCode;//need has encode
										ctrl.company.companyRpts.push(selectedRow);
										ctrl.company['companyRpts' + $filter('encode')(ctrl.companyRpt.serviceCode)].push(selectedRow);
									});
									if (!ctrl.company.companyRptsTmp || ctrl.company.companyRptsTmp.length == 0)
										ctrl.company.companyRptsTmp = ctrl.company['companyRpts' + $filter('encode')(ctrl.companyRpt.serviceCode)] || [];
								}
							}				   
						});	
				});
				
			}
			
			ctrl.editReport = function(row) {
				var params = {};
				var _selectedCompanyReport = row.entity;
				params.companyRpt = angular.copy(_selectedCompanyReport);
				params.companyRpt.filterReportCodes = [];
				params.companyRpt.companyCode = $filter('encode')(ctrl.company.companyCode);
				if(row.entity.reportFormats){
					params.companyRpt.reportFormatsList = [];
					var fieldArr = row.entity.reportFormats.split(",");
					for(var i = 0; i < fieldArr.length; i++){
						if(fieldArr[i] != ""){
							params.companyRpt.reportFormatsList.push(fieldArr[i]);
						}
					}
				}
				params.companyRpt.localeCode = params.companyRpt.localeCode || "en_US";
				angular.forEach(ctrl.company.companyRpts, function(companyRpt, index) {
					params.companyRpt.filterReportCodes.push(companyRpt.reportCode);
				});
				modalService.openCustomDialogs({
				   'title': 'title.company.report',
				   'dialogsModule' : 'cda.company.rptEdit',
				   'params': params,
				   'btnCallback' : {
						'ok' : function(report) {			
							if (!ctrl.company.companyRpts) {								
								ctrl.company.companyRpts = [];
							}
							if (!(report.dataStatus == 'C' || report.dataStatus == 'U')) {
								if (updateProcessFlag) {
									report.dataStatus = 'U';
								} else {
									report.dataStatus = 'C';
								}
							}
							report.companyCode = ctrl.company.companyCode;//need has encode
							angular.extend(_selectedCompanyReport, report);
						}
					}				   
				});	
			}
			
			ctrl.viewReport = function(row) {
				var params = {};
				params.companyRpt = row.entity;
				if (ctrl.companyOld && ctrl.companyOld.companyRpts) {
					var oldModel4SelectedRow;
					angular.forEach(ctrl.companyOld.companyRpts, function(companyRpt, index) {
						if (companyRpt.companyRptId == params.companyRpt.companyRptId) {
							oldModel4SelectedRow = companyRpt;
						}
					});
					params.companyRptOld = oldModel4SelectedRow;
				}
				modalService.openCustomDialogs({
				   'title': 'title.company.report',
				   'dialogsModule' : 'cda.company.rptView',
				   'params': params   
				});	
			}
			
			ctrl.removeReport = function(currRow) {
				// delete from ctrl.company.companyRpts
				angular.forEach(ctrl.selectedCompanyRpts, function(selectedCompanyRpt, key) {
					angular.forEach(ctrl.company.companyRpts, function(companyRpt, index) {
						if (companyRpt.$$hashKey == selectedCompanyRpt.$$hashKey) {
							if (companyRpt.dataStatus =='C') {
								ctrl.company.companyRpts.splice(index, 1);
							} else {
								companyRpt.dataStatus = 'D';
							}
						}
					});
				});
			}
		}
		
		function initAddress($scope, ctrl, updateProcessFlag) {
			if(ctrl.validatorConfig) ctrl.layoutConfig.formConfigs.address.tableConfigs.table.validatorConfig = ctrl.validatorConfig.companyAddrs;
			//init companyAddrs
			ctrl.addressInnerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.address.tableConfigs.table, addressRowSelectionChanged);
			ctrl.addressInnerGridOptions.data = 'vm.company.companyAddrs';
			ctrl.addressInnerGridOptions.verifyData = 'vm.companyOld.companyAddrs';
			function addressRowSelectionChanged(eventRow, selectedRows) {
				ctrl.selectedCompanyAddrs = selectedRows;
			}
			
			
			ctrl.addAddr = function(row) {
				return $q(function(resolved, rejected){
					modalService.openCustomDialogs({
						   'title': 'title.company.address',
						   'dialogsModule' : 'cda.company.addrEdit',
						   'params': {},
						   'btnCallback' : {
								'ok' : function(address) {		
									if (!ctrl.company.companyAddrs) {								
										ctrl.company.companyAddrs = [];
									}  
									address.dataStatus = 'C';
									angular.extend(row, address);
									resolved();
									
								},
							    'close' : function(){
								   rejected();
							    }
							}				   
						});	
				});
						
			}
			
			
	
			
			ctrl.editAddr = function(row) {
				var params = {};
				params.companyAddr = row.entity;
				modalService.openCustomDialogs({
				   'title': 'title.company.address',
				   'dialogsModule' : 'cda.company.addrEdit',
				   'params':  params,
				   'btnCallback' : {
						'ok' : function(address) {			
							if (!ctrl.company.companyAddrs) {								
								ctrl.company.companyAddrs = [];
							}
							if (!(address.dataStatus == 'C' || address.dataStatus == 'U')) {
								if (updateProcessFlag) {
									address.dataStatus = 'U';
								} else {
									address.dataStatus = 'C';
								}
							}
							angular.extend(row, address);						
						}
					}				   
				});	
			}
			
			
			ctrl.viewAddr = function(row) {
				var params = {};
				// for show selected address on popup page
				params.companyAddr = row.entity;
				if (ctrl.companyOld && ctrl.companyOld.companyAddrs) {
					var oldModel4SelectedRow;
					angular.forEach(ctrl.companyOld.companyAddrs, function(address, index) {
						if (address.companyAddrId == params.companyAddr.companyAddrId) {
							oldModel4SelectedRow = address;
						}
					});
					params.companyAddrOld = oldModel4SelectedRow;
				}
				modalService.openCustomDialogs({
				   'title': 'title.company.address',
				   'dialogsModule' : 'cda.company.addrView',
				   'params':  params  
				});	
			}
		}
		
		function initDynaParm($scope, ctrl, updateProcessFlag) {
			ctrl.selectedPropertyInnerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.custProfile.tableConfigs.tableSele, dynaParmSeleRowSelectionChanged);
			ctrl.selectedPropertyInnerGridOptions.data = 'vm.company.companyProps';//dynamicParams
			ctrl.selectedPropertyInnerGridOptions.verifyData = 'vm.companyOld.companyProps';
			ctrl.selectedPropertyInnerGridOptions.multiSelect = true;
			function dynaParmSeleRowSelectionChanged(eventRow, selectedRows) {
				ctrl.selectedDynaParmSeleRows = selectedRows;
			}
			
			if (ctrl.layoutConfig.formConfigs.custProfile.tableConfigs.tableAvai) {
				ctrl.hasAvailablePropertyInnerGrid = 'Y';
				ctrl.availablePropertyInnerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.custProfile.tableConfigs.tableAvai, dynaParmAvaiRowSelectionChanged);
				ctrl.availablePropertyInnerGridOptions.data = 'vm.availableProperties';
				ctrl.availablePropertyInnerGridOptions.multiSelect = true;
				function dynaParmAvaiRowSelectionChanged(eventRow, selectedRows) {
					ctrl.selectedDynaParmAvaiRows = selectedRows;
				}
			}
			
			ctrl.addCompanyProp = function(){
				if (!ctrl.selectedDynaParmAvaiRows || ctrl.selectedDynaParmAvaiRows.length == 0) {
					modalService.openErrorDialogs({
						messages : [ 'js.info.common.item-need-first-select' ]
					});
					return;
				}
				if (!ctrl.company.dynamicParams) {								
					ctrl.company.dynamicParams = {};
				}
				angular.forEach(ctrl.selectedDynaParmAvaiRows, function(selectedDynaParmAvai, key) {
					angular.forEach(ctrl.availableProperties, function(availableProperty, index) {
						if (availableProperty.$$hashKey == selectedDynaParmAvai.$$hashKey) {
							ctrl.availableProperties.splice(index, 1);
							// some new add not in site.dynamicParams, so need put it in
							if (!ctrl.company.dynamicParams[availableProperty.name] || !ctrl.company.dynamicParams[availableProperty.name].value) {
								ctrl.company.dynamicParams[availableProperty.name] = availableProperty;
								availableProperty.dataStatus = 'C';
								angular.merge(availableProperty, availableProperty.dynamicParameter);
							}
							// change 
							var corProf = angular.copy(availableProperty);
							corProf.dynamicParams = {};
							corProf.dynamicParams[availableProperty.name] = availableProperty;
							ctrl.company.companyProps.push(corProf);
						}
					});
				});
				
				ctrl.selectedDynaParmAvaiRows = [];
				
			};

			ctrl.removeCompanyProp = function(){
				if (!ctrl.selectedDynaParmSeleRows || ctrl.selectedDynaParmSeleRows.length == 0) {
					modalService.openErrorDialogs({
						messages : [ 'js.info.common.item-need-first-select' ]
					});
					return;
				}
				angular.forEach(ctrl.selectedDynaParmSeleRows, function(selectedParam, key) {
					angular.forEach(ctrl.company.companyProps, function(companyProp, index) {
						if (companyProp.$$hashKey == selectedParam.$$hashKey) {
							// clear for delete, 
							delete ctrl.company.dynamicParams[companyProp.name];
							
							ctrl.company.companyProps.splice(index, 1);
							ctrl.availableProperties.push(companyProp);
						}
					});
				});
				
				ctrl.selectedDynaParmSeleRows = [];
				
			};
			
			ctrl.resetDynaProperties = function () {
				resetSelectedProperties();
				resetAvailableProperties();
			};
			
			function resetSelectedProperties () {
				if (!ctrl.company.companyProps) {								
					ctrl.company.companyProps = [];
				}
				//ctrl.company.companyProps
				var dynamicParams = ctrl.company.dynamicParams;
				if (dynamicParams) {
					angular.forEach(dynamicParams, function(dynamicParam, key) {
						// some new add prop or exist prop, then remove, also commit to server but value is empty, so need add '&& dynamicParam.value' to check
						if (dynamicParam.subCategory == 'CUSTOMERPROFILE' && dynamicParam.value) {
							ctrl.company.companyProps.push(dynamicParam);
						}
					});
				}
				
				if (ctrl.companyOld) {
					if (!ctrl.companyOld.companyProps) {								
						ctrl.companyOld.companyProps = [];
					}
					//ctrl.company.companyProps
					var oldDynamicParams = ctrl.companyOld.dynamicParams;
					if (oldDynamicParams) {
						angular.forEach(oldDynamicParams, function(dynamicParam, key) {
							// some new add prop or exist prop, then remove, also commit to server but value is empty, so need add '&& dynamicParam.value' to check
							if (dynamicParam.subCategory == 'CUSTOMERPROFILE' && dynamicParam.value) {
								// change, build some dynaparm define
								var corProf = angular.copy(dynamicParam);
								// need dynamicParameter.name and dynamicParameter.dispKey
								corProf.dynamicParameter = angular.copy(dynamicParam);
								// value is such as dynamicParams.CDA_DYNAPARM2.value
								ctrl.companyOld.companyProps.push(corProf);
							}
						});
					}
				}
			}
			
			function resetAvailableProperties () {
				// change layoutConfig, get subCata 'CUSTOMERPROFILE'
				var custProfAvaiProps = [];
				var gridConfigs = ctrl.layoutConfig.formConfigs.custProfile.gridConfigs;
				if (gridConfigs) {
					angular.forEach(gridConfigs, function(gridConfig, key) {
						if (gridConfig.dynamicParameter && gridConfig.dynamicParameter.subCategory == 'CUSTOMERPROFILE') {
							//
							var dynaParm = angular.copy(gridConfig);
							var hasDyna = false;
							if (ctrl.company.companyProps && ctrl.company.companyProps.length > 0) {
								for (var i = 0; i < ctrl.company.companyProps.length; i++) {
									var companyProp = ctrl.company.companyProps[i];
									if ($filter("encode")(companyProp.id) == $filter("encode")(dynaParm.dynamicParameter.id)) {
										hasDyna = true;
										delete companyProp.label;
										// change 
										var corProf = dynaParm;
										corProf.dynamicParams = {};
										corProf.dynamicParams[companyProp.name] = companyProp;
										// only for update verify
										corProf.primaryKey = companyProp.primaryKey;
										corProf.value = companyProp.value;
										ctrl.company.companyProps[i] = corProf;
										break;
									}
								}
							}
							if (!hasDyna)
								custProfAvaiProps.push(dynaParm);
							//this will in tab cust Profile, not show other place
							//gridConfig.show = false;
						}
					});
				}
				// some has value but not has layout dynaparm, need clear
				if (ctrl.company.companyProps && ctrl.company.companyProps.length > 0) {
					for (var i = ctrl.company.companyProps.length - 1; i >= 0 ; i--) {
						var companyProp = ctrl.company.companyProps[i];
						if (!companyProp.dynamicParams) {
							ctrl.company.companyProps.splice(i, 1);
						}
					}
				}
				ctrl.availableProperties = custProfAvaiProps;
				
				sortDynamicParamters(ctrl.company.companyProps);
				sortDynamicParamters(ctrl.availableProperties);
			};
			
			function sortDynamicParamters(serviceDymamicParamters){
				if(!serviceDymamicParamters){
					return;
				}
				serviceDymamicParamters.sort(function(p1, p2){
					return arithService.gt(p1.dynamicParameter.dispOrder, p2.dynamicParameter.dispOrder) ? 1 : -1;
				});
			}
		}
		function initEdiProfileGrid($scope, ctrl) {
			//init initEdiProfile grid
			if(ctrl.validatorConfig && ctrl.validatorConfig.companyEdiProfile) ctrl.layoutConfig.formConfigs.ediFileDeli.tableConfigs.table.validatorConfig = ctrl.validatorConfig.companyEdiProfile.companyEdiFileDelis;
			ctrl.ediFileDeliInnerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.ediFileDeli.tableConfigs.table, ediFileDeliRowSelectionChanged);
			ctrl.ediFileDeliInnerGridOptions.data = 'vm.company.companyEdiProfile.companyEdiFileDelis';
			ctrl.ediFileDeliInnerGridOptions.verifyData = 'vm.companyOld.companyEdiProfile.companyEdiFileDelis';
			function ediFileDeliRowSelectionChanged(eventRow, selectedRows) {
				ctrl.selectedEdiFileDelis = selectedRows;
			}
			ctrl.addEdiFileDeli = function(row) {
				return $q(function(resolved, rejected){
					if (!ctrl.company.companyEdiProfile.companyEdiFileDelis) {
						ctrl.company.companyEdiProfile.companyEdiFileDelis = [];
					}
					var item = {
						fileType : '*',
						companyType : '*',
						deliFlag : 'Y',
						deliSvcName : '',
						filenameFixFlag : 'N',
						filenamePrefix : '',
						filenameSuffix : '',
						filenameMiddle : '',
						deliPriority : 4
					};
					item.dataStatus = 'C';
					ctrl.company.companyEdiProfile.companyEdiFileDelis.push(item);	
				});
					
			};
			
		}
		function initEdiProfile($scope, ctrl) {
			if(!ctrl.company.companyEdiProfile) ctrl.company.companyEdiProfile = {};
			ctrl.company.ediProfileCode = $filter('encode')(ctrl.company.companyCode);
			ctrl.ediProfileTypeChanged = function (){
				var ediProfileType = ctrl.company.companyEdiProfile.ediProfileType;
				ctrl.company.ediProfileType = ediProfileType;
				//set default value.
				ctrl.company.companyEdiProfile.activeFlag = ctrl.company.companyEdiProfile.activeFlag || "Y";
				ctrl.company.companyEdiProfile.overrideSiteId = ctrl.company.companyEdiProfile.overrideSiteId || "N";
			};
			ctrl.ediProfileTypeChanged();
			ctrl.ediFileDeliChanged = function (obj, form) {
				if(form.$dirty && 'C' != obj.dataStatus) obj.dataStatus = 'U';
			}
			ctrl.ediFileDeliCompanyTypeChanged  = function (obj, form) {
				if(form.$dirty && 'C' != obj.dataStatus) obj.dataStatus = 'U';
				if (!obj.companyType || obj.companyType == '') {
					obj.companyType = "*";
				}
			}
		}
		
		return {
			dateDisabled : dateDisabled,
			getCompanyOptions : getCompanyOptions,
			initGeneral : initGeneral,
			initContact : initContact,
			initService : initService,
			initSubCompany: initSubCompany,
			initNotify: initNotify,
			initReport: initReport,
			initAddress: initAddress,
			initDynaParm: initDynaParm,
			initEdiProfileGrid: initEdiProfileGrid,
			initEdiProfile: initEdiProfile
		};
	}
})(angular);
